#!/usr/bin/perl -w
use strict;
use Getopt::Long;
use lib "/net/cpp-group/Leo/bin";
#88888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Usage

#88888888888888888888888888888888888888888888888888888888888888888888888888888888
my $usage = <<'USAGE';

USAGE:

    seq_pairs_split_clusters_by_size.pl
							--path clusters.ks
							--file_size 100000
                            < cluster.pairs

		Takes the output of seq_pairs_cluster_by_single_linkage and
		splits by
        This script takes files supplied via
        STDIN or on the command line and prints the fasta sequence lengths
USAGE

#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888

#   Get options

#88888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
# mandatory


# optional parameters
my $help = undef;
my $path = 'clusters.ks';
my $file_size_limit = 100000;
GetOptions(
			'help' => \$help,
			'path:s' => \$path,
			'file_size:s' => \$file_size_limit,
			);

die $usage if ($help);
die $usage unless ($path && $file_size_limit);


my $file_name = $path;
my $base_name = $file_name;
my $ext = '';
if ($file_name =~ /^(.*)(\..*)$/)
{
	$base_name = $1;
	$ext = $2;
}

my $curr_size = $file_size_limit;
my $file_cnt = -1;

open OUTPUT, ">$base_name.0$ext" or
		die "Error\n\tCould not open $base_name.$file_cnt$ext\n$!";
while (<STDIN>)
{
	if (/>cluster# \d+ size= (\d+)/)
	{
		$curr_size += $1 * $1 * $1 * $1;
		if ($curr_size > $file_size_limit)
		{
			$curr_size = 0;
			++$file_cnt;
			close OUTPUT;
			open OUTPUT, ">$base_name.$file_cnt$ext" or
				die "Error\n\tCould not open $base_name.$file_cnt$ext\n$!";
		}
	}
	print OUTPUT;
}
